<template>
	<div>
		<el-form :inline="true"  style="padding-top: 10px;padding-left: 5px;">
			<el-form-item label="起止日期" prop="startandend" label-width="80px">
				<el-date-picker v-model="startandend" type="daterange" align="right" value-format="yyyy-MM-dd" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions2">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="查询条件" prop="parameter" label-width="80px">
				<el-input v-model="parameter" style="width: 200px;" placeholder="请输入单号"></el-input>
			</el-form-item>
			<el-form-item>
				<div style="float: left;">
					<el-button type="primary" @click="querybutton">查询</el-button>
				</div>
			</el-form-item>
			<el-form-item>
				<div style="float: left;margin-left: -10px;">
					<el-button type="primary" @click="showExport">新增入库</el-button>
				</div>
			</el-form-item>
		</el-form>
		<el-table :data="putData" showOverflowTooltip :max-height="tabHeight"  style="width: 100%" stripe border tooltip-effect="dark">
			<!--<el-table-column type="selection" width="50" > </el-table-column>-->
			<el-table-column prop="put_id" label="单号" show-overflow-tooltip></el-table-column>
			<el-table-column prop="create_time" label="入库时间" show-overflow-tooltip></el-table-column>
			<el-table-column prop="note" label="备注" show-overflow-tooltip></el-table-column>
			<el-table-column label="操作" width="160">
				<template slot-scope="scope">
					<el-button size="small" type="primary" @click="showServerEdit(scope.$index,scope.row)">详情</el-button>
					<!-- <el-button size="small" type="primary" @click="delServerEdit(scope.$index,scope.row)">删除</el-button> -->
				</template>
			</el-table-column>
		</el-table>
		
		
		<el-dialog title="新增入库" :visible.sync="DialogVisible" :close-on-click-modal="false" custom-class='el-dialog--large' width="80%">
			<el-form :inline="true" :model="addForm"  ref='addForm'>
				<!-- <el-form-item label="单号" prop="consignee">
					<el-input v-model="addForm.orderid"></el-input>
				</el-form-item> -->
				
				<el-form-item label="入库日期" prop="create_time">
					<el-date-picker v-model="addForm.create_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择入库日期" style='width:100%'></el-date-picker>
				</el-form-item>
				<el-form-item label="备注" prop="note">
					<el-input v-model="addForm.note" type="textarea" :rows="2"></el-input>
				</el-form-item>
				<div class='right'>
					<el-form-item>
						<el-button type="primary" @click="addNewTr">增加项目</el-button>
					</el-form-item>
				</div>
				<div style="dialogstyle">
					<el-table :data="orderGoodsTable" border class='marginBottom' style="max-height: 500px;overflow: auto;">
						<el-table-column label="商品" width="">
							<template slot-scope='scope'>
								<el-select v-model="scope.row.supplier" placeholder="请选择" @change="changgoods(scope.$index, scope.row)" filterable style='width:100%'>
									<el-option v-for="(item,index) in goods_stockData" :key="index" v-if="selectgoodsData.indexOf(item.gid)<0"  :label="item.goods_id + item.goods_name + item.color_name + item.size_name" :value="item"></el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="商品编码" width="">
							<template slot-scope='scope'>
								<el-input size="small" disabled v-model="scope.row.goods_id"></el-input>
							</template>
						</el-table-column>
								
						<el-table-column label="商品名称" width="">
							<template slot-scope='scope'>
								<el-input size="small" disabled v-model="scope.row.goods_name"></el-input>
							</template>
						</el-table-column>
								
						<el-table-column label="尺码" width="">
							<template slot-scope="scope">
								<el-input disabled v-model="scope.row.size_id"></el-input>
							</template>
						</el-table-column>
								
						<el-table-column label="颜色" width="">
							<template slot-scope='scope'>
								<el-input disabled v-model="scope.row.color_id"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="数量" width="">
							<template slot-scope='scope'>
								<el-input v-model="scope.row.quantity" type="number"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">
								<i class="el-icon-plus" title='添加一行' @click="addNewTr"></i>
								<i class="el-icon-delete" title='删除' @click="currentTrDel(scope.$index, scope.row)"></i>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div class='center'>
					<el-form-item>
						<el-button type="primary" @click="save_CheckIn(1,'addForm')">保存</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="reset_CheckIn">重置</el-button>
					</el-form-item>
				</div>
			</el-form>
		</el-dialog>
		
		<el-dialog title="入库详情" :visible.sync="dialogorder" >
			<el-form :inline="true" :model="goodsputForm" >
				<el-form-item label="入库单号" prop="put_id">
					<el-input v-model="goodsputForm.put_id"></el-input>
				</el-form-item>
				<el-form-item label="入库时间" prop="create_time">
					<el-input v-model="goodsputForm.create_time"></el-input>
				</el-form-item>
				<el-form-item label="备注" prop="note">
					<el-input v-model="goodsputForm.note"></el-input>
				</el-form-item>
			</el-form>
			<el-table :data="recordData" showOverflowTooltip stripe border tooltip-effect="dark" style="overflow: auto;max-height: 500px;">
				<el-table-column prop="goods_id" label="商品编码" show-overflow-tooltip></el-table-column>
				<el-table-column prop="goods_name" label="商品名称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="size_name" label="尺码" show-overflow-tooltip></el-table-column>
				<el-table-column prop="color_name" label="颜色" show-overflow-tooltip></el-table-column>
				<el-table-column prop="quantity" label="数量" show-overflow-tooltip></el-table-column>
			</el-table>
		</el-dialog>
	</div>
</template>

<script>
	import axios from 'axios';
	import { selectallstorage,selectpubbyid,selectpubrecordbyid,selectallstock,insert_putstorage } from '../../api/goods.js'
	export default {
		data() {
			return {
				putData:[],
				goodsData:[],
				parameter:'',
				startandend:[],
				DialogVisible:false,
				addForm:{
					'put_id':'',
					'create_time':'',
					'note':''
				},
				orderGoodsTable:[],
				pickerOptions2: {},
				goodsputForm:{
					'put_id':'',
					'create_time':'',
					'note':''
				},
				dialogorder:false,
				recordData:[],
				goods_stockData:[],
				selectgoodsData:[],
				tabHeight:500
			};
		},
		methods:{
			get_stockList() {
			  selectallstock().then(response => {
				  if(response.code ==0 ){
				  	this.goods_stockData = response.data;
					for(let i=0;i<this.goods_stockData.length;i++){
						this.goods_stockData[i].gid = i;
					}
				  }
				
				// console.log(this.goods_stockData,'this.goods_stockData');
			  })
			},
			querybutton(){
				this.putData = [];
				if( this.startandend == []){
					if(this.startandend[0] == undefined){
						this.startandend[0] = '';
					}
					if(this.startandend[1] == undefined){
						this.startandend[1] = '';
					}
				}
				if(this.startandend == null ){
					this.startandend = [];
					this.startandend[0] = '';
					this.startandend[1] = '';
				}
				selectpubbyid({parameter:this.parameter,parameter1: this.startandend[0],parameter2: this.startandend[1]}).then(response => {
				    if(response.code ==0 ){
						this.putData = response.data;
					}
				})
			},
			get_putList() {
			  selectallstorage().then(response => {
				// console.log(response,'response22');
				if(response.code ==0 ){
					this.putData = response.data;
				}
			  })
			},
			get_putrecordbyid(val){
				this.recordData = [];
				selectpubrecordbyid({parameter:val}).then(response => {
					if(response.code ==0 ){
						this.recordData = response.data;
					}
				})
			},
			showExport(){
				 // 清空数组，初始化，实现清除上一次数据
				var l = this.orderGoodsTable.length;
				this.orderGoodsTable.splice(0,l);
				this.DialogVisible = true;
				this.addForm = {
				    note:'',
					put_id:'',
				    // 自动获取当前时间
				    create_time:'',
				};
				// 添加一条空白数据（设置id为1）即实现默认添加一行，
				this.orderGoodsTable.push({oid:1});
			},
			changgoods:function(index, row){
				// console.log(row,'row',index,row.supplier.id);
				let hindex = 0;
				for(let i=0;i<this.goods_stockData.length;i++){
					if(row.supplier.gid == this.goods_stockData[i].gid){
						hindex = i;
						break;
					}
				}
				this.orderGoodsTable[index]=this.goods_stockData[hindex];
				this.orderGoodsTable[index].quantity = 1;
			},
			save_CheckIn:function(type,formName){
				if(this.addForm.create_time == '' || this.addForm.create_time == null){
					 this.$notify({
						  title: '警告',
						  message: '日期不能为空',
						  type: 'info',
						})
						return ;
				}
				if(this.orderGoodsTable[0].goods_id == '' || this.orderGoodsTable[0].goods_id == undefined){
					 this.$notify({
						  title: '警告',
						  message: '请选择商品',
						  type: 'info',
						})
						return ;
				}
				
				
				
				let num='';
				for(let i=0;i<7;i++){
					num+=Math.floor(Math.random()*10)
				}
				num = num.toString();
				let nowdate = '';
				let date = new Date();
				nowdate = (date.getFullYear()+ ((date.getMonth()+1)<10?'0'+(date.getMonth()+1):(date.getMonth()+1)) + ((date.getDate())<10?'0'+(date.getDate()):(date.getDate()))).toString();
				this.addForm.put_id ='P' + nowdate + num;
				
				for(let i=0;i<this.orderGoodsTable.length;i++){
					this.orderGoodsTable[i].put_id = this.addForm.put_id;
				}
				// console.log(this.orderGoodsTable,'orderGoodsTable')
				insert_putstorage(this.addForm).then(() => {
				  this.$notify({
				    title: '成功',
				    message: '创建成功',
				    type: 'success',
				    duration: 2000
				  })
				  this.querybutton();
				})
				console.log(this.orderGoodsTable,'this.orderGoodsTable')
				axios({
				  method: 'post',
				  url: '/api/insert_put_record',
				  headers: {
					'Content-Type': 'application/json;charset=UTF-8'
				  },	 
					data:  this.orderGoodsTable
				}).then((res) => {
					 this.$notify({
					  title: '成功',
					  message: '创建成功',
					  type: 'success',
					  duration: 2000
					})
				})
				this.DialogVisible = false;
				
			},
			 addNewTr:function(){
			    // 数据长度即为行数，也等同于最后一行的id，加一即为新增行id，
			    var l = this.orderGoodsTable.length;
			    // 数组内push一个空对象
			    this.orderGoodsTable.push({oid:l+1});
			    for(let i=0;i<this.goods_stockData.length;i++){
			    	for(let j=0;j<this.orderGoodsTable.length;j++){
			    		if( this.orderGoodsTable[j].gid == this.goods_stockData[i].gid){
			    			if(this.selectgoodsData.indexOf(this.orderGoodsTable[j].gid)<0){
			    				this.selectgoodsData.push(this.orderGoodsTable[j].gid);
			    			}
			    		}
			    	}
			    }
			},
			 reset_CheckIn:function(){ 
			    var l = this.orderGoodsTable.length;
			    this.orderGoodsTable.splice(0,l);
			    this.orderGoodsTable.push({id:1});
			},
			cloneAddThisTr:function(index, row){
			    var rowStr = JSON.stringify(row);
			    var row = JSON.parse(rowStr);
			    var l = this.orderGoodsTable.length;
			    // 对复制的row的id加一，
			    row.id = l+1;
			    // var row = JSON.parse(JSON.stringify(row));
			    // 复制上一行数据添加到新行，但导致两行数据双向绑定、同步被修改
			    // 因为当前行的 row 数据并不是一个纯粹的JSON对象，经转换为JSON字符串再转换回JSON对象，成为纯粹的JSON对象，添加到数据数组对象里，则不会和当前 row 产生数据双向绑定，
			    this.orderGoodsTable.push(row);
			},
			
			// 删除当前行
			currentTrDel: function(index, row) {
			    // console.log('index：' + index);
			    // console.log(row);
			    this.$confirm('确认删除该记录吗?', '提示', {
			        type: 'warning'
			    }).then(() => {
			        // id 为准备删除的数据的id，这些数据只存在于当前页面，所以只需要这些数据的id不重复即可，
			        let para = { id: row.id };
					this.orderGoodsTable.splice(index,1);
					for(let i=0;i<this.selectgoodsData.length;i++){
						if(row.gid ==this.selectgoodsData[i]){
							this.selectgoodsData.splice(i,1);
						}
					}
			    }).catch(() => {
			
			    });
			},
			showServerEdit(index, row) {
				this.dialogorder = true;
				this.goodsputForm.put_id = row.put_id;
				this.goodsputForm.create_time = row.create_time;
				this.goodsputForm.note = row.note;
				this.get_putrecordbyid(row.put_id);
				// this.selectRow=row;
			},
			delServerEdit(index, indexPath) {
				this.$confirm('是否确定删除'+indexPath.put_id+'订单?', '提示', {
					confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'
				}).then(() => {
				let jsonparas = [];
					apiparas.pushPara(jsonparas, 'put_id', indexPath.put_id);
					let _paras = apiparas.getParas('default', 'sys|del_server_tableColumns', jsonparas);
					execute(_paras).then(response => {
						if(response.errid == 0) {
							this.$notify({
								title: '删除',message: '成功删除',type: 'success'
							});
							this.getDict();
						} else {
							this.$notify.error({
								title: '错误',message: '删除失败'
							});
						}
					});
					this.getDict();
				}).catch(() => {
					this.$message({
						type: 'info',message: '已取消删除'
					});
				});
			},
		
		},
		created(){
			this.tabHeight = document.documentElement.scrollHeight - 160 || document.body.scrollHeight -160;
			this.get_putList();
			this.get_stockList();
		}
	}
</script>

<style>
.marginBottom {
    margin-bottom: 20px;
}
.dialogstyle{
	height: 200px;
	overflow-y: auto;
	overflow-x: hidden;
}
</style>
